package com.isunland.managesystem.ui;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import com.isunland.managesystem.utils.MyStringUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ProjectInfoListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.ProjectCollectOriginal;
import com.isunland.managesystem.entity.DictionaryTreeContent;
import com.isunland.managesystem.entity.ProjectCollectOriginal.ProjectCollectContent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ProjectInfoListFragment extends BaseListFragment {

  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.ProjectInfoListFragment.EXTRA_CONTENT";

  private static final int REQUIRE_DATA = 0;
  private static final int REQUIRE_STAGE = 1;
  private static final int REQUIRE_SEARCH = 2;
  private ProjectInfoListAdapter mAdapter;
  private ArrayList<ProjectCollectContent> mlist;
  private EditText etprojectName;
  private TextView tvregDate;

  private String projectName = "";
  private String regDate = "";
  private String regDateName = "";
  //查询条件
  private String mStartTime = "";
  private String mEndTime = "";
  private String mProjectType = "";
  private String mProjectTypeId = "";
  private String mProjectName = "";

  //开始是否加载和显示空视图
  @Override protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    super.isPostStart(false, false);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("项目选择");
    //初始化查询时间
    mStartTime = MyDateUtil.dateToString(MyDateUtil.getBeforeMonth(3), MyDateUtil.TYPE_DATE);
    mEndTime = MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE);
    //获取查询日期
    volleyGetDate();

  }

  private void volleyGetDate() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DATA_DICTIONARY_LIST);
    HashMap<String, String> params = new HashMap<>();
    params.put("dictFlg", "regDate");
    params.put("andriodUser", "true");
    params.put("memCode", mCurrentUser.getMemberCode());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        DictionaryTreeContent[] dataList = new Gson().fromJson(arg0, DictionaryTreeContent[].class);
        regDate = dataList[dataList.length - 2].getCustomAttrs();
        regDateName = dataList[dataList.length - 2].getName();
        //tvregDate.setText(regDateName);
        ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
        SpannableString spannableString = new SpannableString(MyStringUtil.connect("   ",regDateName));
        spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvregDate.setHint(spannableString);

        volleyPost();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    });
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_project, null, false);

    tvregDate = (TextView) header.findViewById(R.id.tv_search_date);
    tvregDate.setInputType(InputType.TYPE_NULL);
    tvregDate.setTextIsSelectable(true);
    etprojectName = (EditText) header.findViewById(R.id.et_search_project);
    ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
    SpannableString spannableString = new SpannableString("   请输入项目名称");
    spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    etprojectName.setHint(spannableString);
    tvregDate.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        DialogFragment dialog =
            ProjectPropertyDialogFrament.newInstance(ProjectPropertyDialogFrament.regDate);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(ProjectInfoListFragment.this, REQUIRE_DATA);
        dialog.show(fm, "");
      }
    });
    mListview.addHeaderView(header);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_query:
        projectName = etprojectName.getText().toString();
        volleyPost();

        //项目查询界面
        //            CustomerDialog content=new CustomerDialog(mStartTime,mEndTime,mProjectType,mProjectTypeId,mProjectName);
        //            Intent i=new Intent(getActivity(),ProjectSearchActivity.class);
        //            i.putExtra(EXTRA_CONTENT,content);
        //            startActivityForResult(i,REQUIRE_SEARCH);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public String getUrl() {
    return ApiConst.ULR_PROJECT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("projectName", projectName);
    params.put("regDate", regDate);
    params.put("page", "1");
    params.put("rows", "1000");
    params.put("orderField", "project_Sign_Date");
    params.put("orderSeq", "desc");
    return params;
  }

  @Override public void resolveResponse(String json) {
    ProjectCollectOriginal original = new Gson().fromJson(json, ProjectCollectOriginal.class);
    ArrayList<ProjectCollectContent> rows = original.getRows();
    if (mlist == null) {
      mlist = new ArrayList<>();
    }
    mlist.clear();
    mlist.addAll(rows);
    setAdapter(mlist);
  }

  private void setAdapter(ArrayList<ProjectCollectContent> mlist2) {
    if (mAdapter == null) {
      mAdapter = new ProjectInfoListAdapter(mActivity, mlist2);
    }
    setListAdapter(mAdapter);
    ((ProjectInfoListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    ProjectCollectContent content = mlist.get(position - 2);
    Intent i = new Intent(getActivity(), ProjectProgressListActivity.class);
    i.putExtra(ProjectProgressListFragment.EXTRA_CONTENT, content);
    startActivityForResult(i, REQUIRE_STAGE);
    getActivity().setResult(Activity.RESULT_OK, i);
    //		getActivity().finish();

    super.onListItemClick(l, v, position, id);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUIRE_DATA) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      regDateName = customer.getName();
      regDate = customer.getId();
      ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
      SpannableString spannableString = new SpannableString(MyStringUtil.connect("   ",regDateName));
      spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      tvregDate.setHint(spannableString);
    }
    if (requestCode == REQUIRE_STAGE) {
      volleyPost();
    }
    //项目查询界面
    if (requestCode == REQUIRE_SEARCH) {
      CustomerDialog content = (CustomerDialog) data.getSerializableExtra(EXTRA_CONTENT);
      mStartTime = content.getName();
      mEndTime = content.getId();
      mProjectType = content.getJobNo();
      mProjectTypeId = content.getMemberCode();
      mProjectName = content.getDept();
      volleyPost();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
}
